#include "HttpServer.hpp"
#include <memory>
using namespace server;

void Usage(string proc)
{
    cout << "Usage:\n  " << proc << " prot\r\n\r\n";
}
string suffixToDesc(const string suffix)
{
    string ct = "Content-Type: ";
    if (suffix == ".html")
        ct += "text/html";
    else if (suffix == ".gif")
        ct += "image/gif";
    ct += "\r\n";
    return ct;
}
// 1. 服务器和网页分离，html
// 2. url -> / : web根目录
// 3. 我们要正确的给客户端返回资源类型，我们首先要自己知道！所有的资源都有后缀！！
bool Get(const HttpRequest &req, HttpResponse &resp)
{
    cout << "-----------------------------------http start-------------------------------------" << endl;
    cout << req.inbuffer << std ::endl;
    std ::cout << "method: " << req.method << std ::endl;
    std ::cout << "url: " << req.url << std ::endl;
    std::cout << "httpversion: " << req.httpversion << std ::endl;
    std::cout << "path: " << req.path << std ::endl;
    std::cout << "suffix: " << req.suffix << std::endl;
    // std::cout << "size: " << req.size << "字节" << std::endl;
    cout << "-----------------------------------http end-------------------------------------" << endl;

    string respline = "HTTP/1.1 307 Temporary Redirect\r\n";
    string respheader = suffixToDesc(req.suffix);


    string respblan = "\r\n";
    // resp.body = "<html lang=\"en\"><head><meta charset=\"UTF-8\"><title>父亲</title><h1>我你爹！！！！</h1></head><body></body></html>";
    std::string body;
    // body.resize(req.size+1);
    if (!Util::readFile(req.path,&body))
    {
        Util::readFile(html_404, &body); // 一定能成功
    }
    int size = body.size();
    if (size > 0)
    {
        respheader += "Content-Length: ";
        respheader += to_string(size);
        respheader += "\r\n";
    }

    respheader += "Location: https://www.qq.com/\r\n";

    std::cout << "size: " << size << "字节" << std::endl;
    cout << "-----------------------------------http end-------------------------------------" << endl;
    resp.outbuffer += respline;
    resp.outbuffer += respheader;
    resp.outbuffer += respblan;
    cout << "-----------------------------------http response start-------------------------------------" << endl;
    cout << resp.outbuffer << endl;
    cout << "-----------------------------------http response end-------------------------------------" << endl;
    resp.outbuffer += body;

    return true;
}

int main(int args, char *argv[])
{
    if (args != 2)
    {
        Usage(argv[0]);
        exit(0);
    }
    uint16_t port = atoi(argv[1]);
    unique_ptr<HttpServer> httpsvr(new HttpServer(Get, port));
    httpsvr->initServer();
    httpsvr->start();

    return 0;
}